//
//  HMTeacherAttendanceRecordVC.m
//  TEXTS
//
//  Created by 陈辉明 on 2017/12/5.
//  Copyright © 2017年 goldwin. All rights reserved.
//

#import "HMTeacherAttendanceRecordVC.h"
#import "HMTeacherSignInOneCell.h"
#import "HMTeacherSignInTwoCell.h"
#import "JXAlertview.h"
#import "HMTeacherAttendanceRecordModel.h"

@interface HMTeacherAttendanceRecordVC () <UITableViewDataSource,CustomAlertDelegete>
{
    NSInteger _mark;//标记类型
    NSString *_selectDate;//标记选中的日期
    
}

@property (nonatomic,strong) CustomDayDatePicker *datePicker;
@property (nonatomic,assign) BOOL isFirst;
@property (nonatomic,copy) NSString *startStr;
@property (nonatomic,copy) NSString *endStr;
@property (nonatomic,copy) NSString *firstData;
@property(nonatomic,copy) NSString *lastData;

@property (weak, nonatomic) IBOutlet UILabel *starTimeLabel;//开始时间
@property (weak, nonatomic) IBOutlet UILabel *endTimeLabel;//结束时间
@property (weak, nonatomic) IBOutlet UILabel *holidayLabel;//请假次数
@property (weak, nonatomic) IBOutlet UILabel *signUpLabel;//签到次数
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property(nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,assign) BOOL isTrue;
@property (nonatomic,assign) NSInteger page;



@end

@implementation HMTeacherAttendanceRecordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.lastData = [NSString currentDateTow];
    if (self.isJiGou1) {
        self.teacherId = self.isJiGou;
        NSLog(@"%@",self.teacherName);
        self.title = self.teacherName;
    } else {
        self.teacherId = [AccountTool shareAccountTool].currentAccount.uid;
        self.title = [AccountTool shareAccountTool].currentAccount.petName;
    }
    
    [self setUpRefresh];
    [self setUpTableView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
   
}



-(void)setUpTableView {
    
    self.tableView.contentInset = UIEdgeInsetsMake(-54, 0, 0, 0);
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"HMTeacherSignInOneCell" bundle:nil] forCellReuseIdentifier:@"HMTeacherSignInOneCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"HMTeacherSignInTwoCell" bundle:nil] forCellReuseIdentifier:@"HMTeacherSignInTwoCellId"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 60;
    self.endTimeLabel.text = [NSString stringWithFormat:@"%@",self.lastData];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HMTeacherAttendanceRecordModel *model = self.dataSource[indexPath.row];
    
    if ([[NSString stringWithFormat:@"%@",model.type] isEqualToString:@"1"]) {
        HMTeacherSignInOneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HMTeacherSignInOneCellId"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        return cell;
        
    } else if([[NSString stringWithFormat:@"%@",model.type] isEqualToString:@"0"]) {
        HMTeacherSignInTwoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HMTeacherSignInTwoCellId"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
        
    
        
        return cell;
    }
    return nil;
}



#pragma mark - 点击事件



-(NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray new];
    }
    return _dataSource;
}

- (void)setNetWork {
    
    self.signUpLabel.text = @"0";
    self.holidayLabel.text = @"0";
    
    NSDate *date =[NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"yyyy"];
    NSInteger currentYear=[[formatter stringFromDate:date] integerValue];
    [formatter setDateFormat:@"MM"];
    NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];
    [formatter setDateFormat:@"dd"];
    //    NSInteger currentDay=[[formatter stringFromDate:date] integerValue];
    
    
    NSString *yy = [NSString stringWithFormat:@"%ld",currentYear];
    
    NSString *mm = [yy stringByAppendingFormat:@"-%ld",currentMonth];
    self.firstData = [NSString stringWithFormat:@"%@-01",mm];
    
  
    // http://192.168.0.226:8080/StarShine/ys/yxhUser.do?action=getTeacherListRecord&teacherId=&pageNumber=&startTime=&endTime=
   
    NSString *url = [NSString new];
    if (self.isFirst) {
    
        url = [NSString stringWithFormat:@"yxhUser.do?action=getTeacherListRecord&teacherId=%@&startTime=%@&endTime=%@&pageNumber=%ld",self.teacherId,self.startStr,self.endStr,self.page];
        
        
    }else{
        self.starTimeLabel.text = [NSString stringWithFormat:@"%@",self.firstData];
        url = [NSString stringWithFormat:@"yxhUser.do?action=getTeacherListRecord&startTime=%@&endTime=%@&pageNumber=%ld&teacherId=%@",self.firstData,self.lastData,self.page,self.teacherId];
        
    }
 

    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);

    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
    [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD showWithStatus:LLLoading];

    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        
         if ([[Obj valueForKey:@"code"] integerValue] == 1000) {
             [SVProgressHUD dismiss];
             if (self.isTrue == YES) {
                 [self.dataSource removeAllObjects];
             }
             NSDictionary *dict1 =  [Obj valueForKey:@"t"];
             self.signUpLabel.text = [NSString stringWithFormat:@"%@",[dict1 valueForKey:@"signCount"]];
             self.holidayLabel.text = [NSString stringWithFormat:@"%@",[dict1 valueForKey:@"leaveCount"]];
             for (NSDictionary *dict in dict1[@"trList"][@"dataList"]) {
                 HMTeacherAttendanceRecordModel *model = [HMTeacherAttendanceRecordModel HMTeacherAttendanceRecordModelWithDict:dict];
                 [self.dataSource addObject:model];
             }
             
             
             [self.tableView reloadData];
             [self.tableView.mj_footer endRefreshing];
             [self.tableView.mj_header endRefreshing];
             
             
         } else {
              [SVProgressHUD showErrorWithStatus:Obj[@"msg"]];
         }
        
        
        
    } Fail:^(NSError *Error) {
        
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        [SVProgressHUD dismiss];
        
    }];
}

#pragma mark --- 上拉加载和下拉刷新方法的实现
- (void)setUpRefresh{
    
    //下拉刷新
    self.tableView.mj_header  = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    //自动更改透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    //进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    //结束头部刷新
    [self.tableView.mj_header endRefreshing];
    //结束尾部刷新
    [self.tableView.mj_footer endRefreshing];
    
    
}

/**
 *  上拉加载
 */
- (void)upRefresh{
    
    self.isTrue = NO;
    self.page++;
    [self setNetWork];
    
}
/**
 *  下拉刷新
 */

- (void)downRefresh{
    self.isTrue = YES;
    self.page = 1;
    [self setNetWork];
    
    
}

- (IBAction)clickAllButton:(UIButton *)sender {
    NSInteger tag = sender.tag;
    
    if (201 == tag) {
        
        NSLog(@"dd");
        
        JXAlertview *alert = [[JXAlertview alloc]initWithFrame:CGRectMake(10, 0, kScreenWidth - 60, 200)];
        alert.center = self.view.center;
        alert.delegate = self;
        [alert initwithtitle:@"开始时间" andcommitbtn:@"确定" andStr:@"0"];
        [alert addSubview:self.datePicker];
        [alert show];
        
        
        _mark = 1;
        
        
        
    }else{
        
        JXAlertview *alert = [[JXAlertview alloc]initWithFrame:CGRectMake(10, 0, kScreenWidth - 60, 200)];
        alert.center = self.view.center;
        alert.delegate = self;
        [alert initwithtitle:@"结束时间" andcommitbtn:@"确定" andStr:@"0"];
        [alert addSubview:self.datePicker];
        [alert show];
        
        
        _mark = 2;
        
        
    }
    
}


- (void)btnindex:(int)index :(int)tag{
    
    if (index == 2) {
        if (_mark == 1) {
            _selectDate = [NSString stringWithFormat:@"%d-%02d-%02d",self.datePicker.year,self.datePicker.month,self.datePicker.day];
            self.starTimeLabel.text = [NSString stringWithFormat:@"%@",_selectDate];
//            [self.startSelectButton setTitle:[NSString stringWithFormat:@"%@",_selectDate] forState:(UIControlStateNormal)];
        }else if (_mark == 2){
            
            _selectDate = [NSString stringWithFormat:@"%d-%02d-%02d",self.datePicker.year,self.datePicker.month,self.datePicker.day];
//            [self.endSelectButton setTitle:[NSString stringWithFormat:@"%@",_selectDate] forState:(UIControlStateNormal)];
            self.endTimeLabel.text = [NSString stringWithFormat:@"%@",_selectDate];
            
            [self sureButtonAction];
        }
    }
    
    
    
    
}





#pragma mark --- 确定方法的实现
- (void)sureButtonAction{
    
    NSString *start = [self.starTimeLabel.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSString *endSelect = [self.endTimeLabel.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    
    NSComparisonResult result = [start compare:endSelect];
    
    if (result != NSOrderedAscending) {
        [SVProgressHUD showErrorWithStatus:@"结束时间必须大于开始时间!"];
    }else{
        
        
        [self setSetTowSureStart:start endSelect:endSelect];
        
        
        
    }
    
    
    
}


- (void)setSetTowSureStart:(NSString *)startStr endSelect:(NSString *)endSelect{
    
    
    self.isFirst = YES;
    self.startStr = startStr;
    self.endStr = endSelect;
    
    [self.tableView.mj_header beginRefreshing];
    
    
    
    
    
}


- (CustomDayDatePicker *)datePicker {
    
    if (_datePicker == nil) {
        self.datePicker = [[CustomDayDatePicker alloc]initWithFrame:CGRectMake(0, 20, kScreenWidth - 60, 140)];
        
    }
    
    
    return _datePicker;
}

//传入今天的时间，返回明天的时间
- (NSString *)GetTomorrowDay:(NSDate *)aDate {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
    [components setDay:([components day]+1)];
    
    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
    [dateday setDateFormat:@"yyyy-MM-dd"];
    return [dateday stringFromDate:beginningOfWeek];
}


-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
}




@end
